import { Controller, Get, Inject, Query } from '@midwayjs/core';
import { XBMService } from '@service/xbm.service';
import { Context } from '@midwayjs/koa';
import { MqttService } from '@service/mqtt.service';
import * as path from 'path';
import { StudentService } from '@service/firmware/student.service';
import { StudentWristbandService } from '@service/firmware/student_wristband.service';
import { resBuild } from '@utils/resBuild';
import * as fs from 'fs';
@Controller('/xbm')
export class XbmController {
  @Inject()
  ctx: Context;
  @Inject()
  mqttService: MqttService;
  @Inject()
  studentService: StudentService;
  @Inject()
  studentWristbandService: StudentWristbandService;

  @Inject()
  xbmService: XBMService;
  private defaultFontPath: string = path.join(__dirname, '../../dist/upload/otf', 'SourceHanSansSC-Light-2.otf');

  /**
   * 获取XBM格式数据  单次写名字
   */
  @Get('/convert')
  async getXBM(
    @Query('name') name: string,
    @Query('gw_mac') gw_mac: string,
    @Query('wb_mac') wb_mac: string,
    @Query('fontPath') fontPath: string | null = null,
    @Query('pointsize') pointsize: number,
    @Query('outputPath') outputPath: string | null = null
  ) {
    try {
      // 检查默认字体路径是否存在
      if (!this.defaultFontPath) {
        throw new Error('系统错误：未配置默认字体路径，请联系管理员处理');
      }

      // 检查字体文件是否存在（如果不是网络路径）
      if (!this.defaultFontPath.startsWith('http') && !fs.existsSync(this.defaultFontPath)) {
        throw new Error(`系统错误：在路径 ${this.defaultFontPath} 找不到字体文件，请联系管理员`);
      }
      // 4. 准备输出路径
      outputPath = path.join(__dirname, '../../dist/upload/xbm');
      console.log('输出路径', outputPath);
      console.log('网关MAC地址', gw_mac);
      pointsize = 18;
      // 处理所有XBM转换
      let maxWidth = 64;
      const buffer = await this.xbmService.generateXbmWithWidthLimit(
        name,
        maxWidth,
        this.defaultFontPath,
        pointsize,
        outputPath
      );

      const base64Data = Buffer.from(buffer).toString('base64');
      let obj = {
        action: 'xbm',
        list: [
          {
            mac: wb_mac,
            xbm: base64Data
          }],
      }

      // 发送MQTT消息到指定网关写入名称
      this.mqttService.clientXbmToPublish(gw_mac, obj)

      return resBuild.data({ xbm: base64Data });
    } catch (error) {
      console.error('处理XBM数据时出错:', error);
      return resBuild.fail(`处理XBM数据时出错: ${error.message}`);
    }
  }

  /**
   * 下载XBM二进制文件
   */
  @Get('/download')
  async generateXBM(
    @Query('name') name: string,
    @Query('fontPath') fontPath: string,
    @Query('pointsize') pointsize: number = 14,
    @Query('outputPath') outputPath: string | null = null
  ) {
    const buffer = await this.xbmService.textToXbm(name, fontPath, pointsize, outputPath);

    // Optional: Print or visualize
    this.xbmService.printXBMInfo(buffer);
    this.xbmService.visualizeXBM(buffer);

    return { message: 'XBM 生成成功', buffer };
  }


  /**
  * 下发写入名称(批量写名字)
  */
  @Get('/xbmToMqtt')
  async mqttToName(
    @Query() params: { class_id: number, gw_mac: string }
  ) {
    try {
      // 1. 检查默认字体路径是否存在
      if (!this.defaultFontPath) {
        throw new Error('系统错误：未配置默认字体路径，请联系管理员处理');
      }

      // 检查字体文件是否存在（如果不是网络路径）
      if (!this.defaultFontPath.startsWith('http') && !fs.existsSync(this.defaultFontPath)) {
        throw new Error(`系统错误：在路径 ${this.defaultFontPath} 找不到字体文件，请联系管理员`);
      }

      // 2. 获取学生列表
      const students = await this.studentService.getAllStudents(params);
      // 3. 并行获取学生手环关联信息
      const stuWbPromises = students.data.map(async (item) => {
        const result = await this.studentWristbandService.findWristbandByStudentId(item.id);
        return result.data ? { name: item.name, mac: result.data?.mac } : null;
      });

      // 过滤掉无效的条目
      const stuWbList = (await Promise.all(stuWbPromises)).filter(item => item !== null);

      // 4. 准备输出路径
      const outputPath = path.join(__dirname, '../../dist/upload/xbm');
      const pointsize = 18;

      console.log('默认字体路径:', this.defaultFontPath);
      console.log('XBM输出路径:', outputPath);

      let maxWidth = 64;

      // 5. 并行处理所有XBM转换
      const xbmPromises = stuWbList.map(async (item) => {
        const buffer = await this.xbmService.generateXbmWithWidthLimit(
          item.name,
          maxWidth,
          this.defaultFontPath,
          pointsize,
          outputPath
        );

        return {
          mac: item.mac,
          xbm: Buffer.from(buffer).toString('base64')
        };
      });

      const list = await Promise.all(xbmPromises);

      // 6. 如果有数据，发送MQTT消息
      if (list.length > 0) {
        const obj = {
          action: 'xbm',
          list: list
        };
        this.mqttService.clientXbmToPublish(params.gw_mac, obj);
      }

      console.log(`获取了${students.total}个学生`);
      console.log(`成功处理${list.length}个学生`);
      return resBuild.success(`成功处理${list.length}个学生`);

    } catch (error) {
      console.error('处理XBM数据时出错:', error);
      return resBuild.fail(`处理XBM数据时出错: ${error.message}`);
    }
  }
}